//
//  MessageCenter.m
//  QBIM
//
//  Created by liunian on 14-3-17.
//  Copyright (c) 2014年 liunian. All rights reserved.
//

#import "MessageCenter.h"
#import "BodyBase.h"
#import "PacketCenter.h"
#import "MsgParam.h"
#import "HttpRequest.h"
#import "JSON.h"
#import "MessageModel.h"
#import "UIAlertView+Blocks.h"
#import "PayloadBase.h"
#import "JSON.h"
#import "NSData+Gzip.h"
#import "PacketUtility.h"

#define kPacketHeaderLength         8

@interface MessageCenter ()<PacketDelegate>

//心跳请求:(server/client)
- (void)heartBeat;
- (void)packetCenterDidReceiveHeaderBody:(HeaderBody *)headerBody;
@property (nonatomic, retain) AuthPayload *authPayload;
@property (nonatomic, retain) PacketCenter  *centerPacket;
@end

static MessageCenter *staticMessageCenterShared = nil;
@implementation MessageCenter

- (id)initHidden{
    self.centerPacket.delegate = self;
    return [super init];
}

+ (MessageCenter *)shared{
    if (nil == staticMessageCenterShared)
        {
        staticMessageCenterShared = [[MessageCenter alloc] initHidden];
        }
    return staticMessageCenterShared;
}

- (AuthPayload *)currentAuthPayload{
    return _authPayload;
}

- (void)setAuthPayLoad:(AuthPayload *)authPayload{
    self.authPayload = authPayload;
}

#pragma mark paser packet
- (void)paserReceiveData:(NSData *)receiveData{
    
    NSUInteger length = [receiveData length];
    if (length == 0) {
        return;
    }
    
    NSRange range0 = {0,4};
    NSRange range1 = {4,1};
    NSRange range2 = {5,1};
    
    uint32_t  bodyLength = [PacketUtility NSDataToUInt:[receiveData subdataWithRange:range0]];
    PacketType packetType = [PacketUtility NSDataToInt:[receiveData subdataWithRange:range1]];
    PacketFormat packetFormat = [PacketUtility NSDataToInt:[receiveData subdataWithRange:range2]];
    NSData *bodyData = nil;
    
    if (packetFormat == PacketFormatGzip) {
        NSData *zipData = [receiveData subdataWithRange:NSMakeRange(kPacketHeaderLength, bodyLength)];
        bodyData = [zipData gzipUnpack];
    }else{
        NSRange range = {kPacketHeaderLength,bodyLength};
        bodyData = [receiveData subdataWithRange:range];
    }
    NSString *body = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
    if (body == nil)
        {
        return;
        }
    
    HeaderBody *headerBody = [[HeaderBody alloc] initWithBody:body];
    headerBody.packetType = packetType;
    headerBody.packetFormat = packetFormat;
    [self packetCenterDidReceiveHeaderBody:headerBody];
}

- (void)packetCenterDidReceiveHeaderBody:(HeaderBody *)headerBody{
    NSDictionary *jsonDic = [headerBody.bodyJSON JSONValue];
    if (jsonDic == nil) {

        return;
    }
    DBLog(@"================");
    DBLog(@"\npacketType:%d\nbody:%@",headerBody.packetType,jsonDic);
    switch (headerBody.packetType) {
        case PacketTypeDeliveryReport:
        {
        
        }
            break;
        case PacketTypeContentMessageList:
        {
        NSArray *dataArray = [jsonDic objectForKey:@"M"];
        NSMutableArray *mArray = [[NSMutableArray alloc] initWithCapacity:dataArray.count];
        [dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSDictionary *dic = obj;
            MessageContent *content = [MessageContent parmObj];
            content.U = [dic objectForKey:@"U"];
            content.S = [[dic objectForKey:@"S"] intValue];
            content.MT= [[dic objectForKey:@"MT"] intValue];
            content.R= [[dic objectForKey:@"R"] intValue];
            content.PT= [[dic objectForKey:@"PT"] intValue];
            content.P = [dic objectForKey:@"P"];
            content.T = [dic objectForKey:@"T"];
            content.CT = [dic objectForKey:@"CT"];
            [mArray addObject:content];
        }];
        
        MessageBody *mBody = [MessageBody parmObj];
        [mBody setI:[[jsonDic objectForKey:@"I"] intValue]];
        [mBody setM:mArray];
        
         [[NSNotificationCenter defaultCenter] postNotificationName:@"CHART" object:mBody userInfo:nil];
        
        RespBody *respBody = [RespBody parmObj];
        [respBody setI:[[jsonDic objectForKey:@"I"] intValue]];
        [respBody setEC:0];
        
        HeaderBody *body = [[HeaderBody alloc] initWithBody:respBody];
        body.packetType = PacketTypeResponse;
        [self.centerPacket sendPacket:body.prepareSendData];
        
        }
            break;
        case PacketTypeResponse:
        {
        RespBody *respBody = [RespBody parmObj];
        [respBody setI:[[jsonDic objectForKey:@"I"] intValue]];
        [respBody setEC:[[jsonDic objectForKey:@"EC"] intValue]];
        [respBody setEM:[jsonDic objectForKey:@"EM"]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"SYS" message:respBody.EM cancelButtonItem:[RIButtonItem itemWithLabel:@"OK" action:^{
                
            }] otherButtonItems: nil];
            [alertView show];
        });
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LOGIN" object:respBody userInfo:nil];
        
        
        }
            break;
        case PacketTypeHearBeatReq:
        {

        BeatBody *beatBody = [BeatBody parmObj];
        beatBody.I = [[jsonDic objectForKey:@"I"] integerValue];
        beatBody.CT = [jsonDic objectForKey:@"CT"];

        HeaderBody *body = [[HeaderBody alloc] initWithBody:beatBody];
        body.packetType = PacketTypeHearBeatResp;
        [self.centerPacket sendPacket:body.prepareSendData];
        }
            break;
        case PacketTypeHearBeatResp:
        {
        
        }
            break;
        case PacketTypeAuthRequest:
        {
        
        }
            break;
        case PacketTypeSysCMD:
        {
        SysCMDBody *respBody = [SysCMDBody parmObj];
        SysCMDPayload *payload = [SysCMDPayload parmObj];
        NSDictionary *dic = [[jsonDic objectForKey:@"P"] JSONValue];
        
        [payload setCMD:[[dic objectForKey:@"CMD"] intValue]];
        [payload setEC:[[dic objectForKey:@"EC"] intValue]];
        [payload setEM:[dic objectForKey:@"EM"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"SYS-CMD" message:respBody.P.EM cancelButtonItem:[RIButtonItem itemWithLabel:@"OK" action:^{
                
            }] otherButtonItems: nil];
            [alertView show];
        });

        }
            break;
        case PacketTypeSysReport:
        {
        SysCMDBody *respBody = [SysCMDBody parmObj];
        SysCMDPayload *payload = [SysCMDPayload parmObj];
        
        
        [payload setCMD:[[jsonDic objectForKey:@"CMD"] intValue]];
        [payload setEC:[[jsonDic objectForKey:@"EC"] intValue]];
        [payload setEM:[jsonDic objectForKey:@"EM"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"SYS-CMD" message:respBody.P.EM cancelButtonItem:[RIButtonItem itemWithLabel:@"OK" action:^{
                
            }] otherButtonItems: nil];
            [alertView show];
        });

        }
            break;
        default:
            break;
    }

}

#pragma mark method
- (void)auth:(HeaderBody *)body{
    [self.centerPacket sendPacket:body.prepareSendData];
}
- (void)logout{
    [self.centerPacket disConnect];
}
//心跳请求:(server/client)
- (void)heartBeat{

}

- (void)sendMessage:(MsgParam *)msgParam{
    
    NSString *requestUrl = kAPI_SENDMESSAGE;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:msgParam.parm2jsonObj];
    
    SET_PARAM(msgParam.thread,@"thread",params);
    SET_PARAM(app_token,@"token",params);
    SET_PARAM(APPID, @"appid",params);
    
    [HttpRequest requestWithURLStr:requestUrl param:params httpMethod:HttpMethodPost isAsyn:YES completionBlock:^(ASIHTTPRequest *request) {
        DBLog(@"%@",request.responseString);
        NSDictionary *resultDict = [request.responseString JSONValue];
        if ([resultDict objectForKey:@"meta"]) {
            NSDictionary *metaDic = [resultDict objectForKey:@"meta"];

            IMMeta *meta = [IMMeta parmObj];
            meta.code = [[metaDic objectForKey:@"code"] intValue];
            if ([metaDic objectForKey:@"error"]) {
                meta.error = [metaDic objectForKey:@"error"];
            }
            if ([metaDic objectForKey:@"message"]) {
                meta.message = [metaDic objectForKey:@"message"];
            }
            
            if (meta.code == 200) {
                NSDictionary *dataDic = [resultDict objectForKey:@"data"];
                MessageContent *content = [MessageContent parmObj];
                content.U = [dataDic objectForKey:@"U"];
                content.S = [[dataDic objectForKey:@"S"] intValue];
                content.MT= [[dataDic objectForKey:@"MT"] intValue];
                content.R= [[dataDic objectForKey:@"R"] intValue];
                content.PT= [[dataDic objectForKey:@"PT"] intValue];
                content.P = [dataDic objectForKey:@"P"];
                content.T = [dataDic objectForKey:@"T"];
                content.CT = [dataDic objectForKey:@"CT"];
                
                MessageBody *mBody = [MessageBody parmObj];
                [mBody setM:[NSArray arrayWithObject:content]];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"CHART" object:mBody userInfo:nil];
            }
        }
    } failedBlock:^(ASIHTTPRequest *request) {
        DBLog(@"%@",request.responseString);
    }];

}

- (void)subscribe:(int)ID{

    NSString *requestUrl = kAPI_SUBSCRIBE;

    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    SET_PARAM([NSNumber numberWithInt:ID],@"accountid",params);
    SET_PARAM(app_token,@"token",params);
    SET_PARAM(APPID, @"appid",params);

    [HttpRequest requestWithURLStr:requestUrl param:params httpMethod:HttpMethodPost isAsyn:YES completionBlock:^(ASIHTTPRequest *request) {
        DBLog(@"%@",request.responseString);
        NSDictionary *resultDict = [request.responseString JSONValue];
        if ([resultDict objectForKey:@"meta"]) {
            NSDictionary *metaDic = [resultDict objectForKey:@"meta"];
            IMMeta *meta = [IMMeta parmObj];
//            meta.code = [[metaDic objectForKey:@"code"] intValue];
//            if ([metaDic objectForKey:@"error"]) {
//                meta.error = [metaDic objectForKey:@"error"];
//            }
//            if ([metaDic objectForKey:@"message"]) {
//                meta.message = [metaDic objectForKey:@"message"];
//            }

            if (meta.code == 200) {
                NSDictionary *dataDic = [resultDict objectForKey:@"data"];
            }
        }
    } failedBlock:^(ASIHTTPRequest *request) {
        DBLog(@"%@",request.responseString);
          NSDictionary *resultDict = [request.responseString JSONValue];
        if ([resultDict objectForKey:@"meta"]) {
            NSDictionary *metaDic = [resultDict objectForKey:@"meta"];
            IMMeta *meta = [IMMeta parmObj];
        }
    }];
}

- (void)unsubscribe:(int)ID{
    NSString *requestUrl = kAPI_UNSUBSCRIBE;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    SET_PARAM([NSNumber numberWithInt:ID],@"accountid",params);
    SET_PARAM(app_token,@"token",params);
    SET_PARAM(APPID, @"appid",params);

    [HttpRequest requestWithURLStr:requestUrl param:params httpMethod:HttpMethodPost isAsyn:YES completionBlock:^(ASIHTTPRequest *request) {
        DBLog(@"%@",request.responseString);
        NSDictionary *resultDict = [request.responseString JSONValue];
        if ([resultDict objectForKey:@"meta"]) {
            NSDictionary *metaDic = [resultDict objectForKey:@"meta"];
            IMMeta *meta = [IMMeta parmObj];
            meta.code = [[metaDic objectForKey:@"code"] intValue];
            if ([metaDic objectForKey:@"error"]) {
                meta.error = [metaDic objectForKey:@"error"];
            }
            if ([metaDic objectForKey:@"message"]) {
                meta.message = [metaDic objectForKey:@"message"];
            }

            if (meta.code == 200) {
                NSDictionary *dataDic = [resultDict objectForKey:@"data"];
            }
        }
    } failedBlock:^(ASIHTTPRequest *request) {
        DBLog(@"%@",request.responseString);
    }];
}

#pragma mark PacketDelegate
- (void)packetCenter:(PacketCenter *)packetCenter didConnectToHost:(NSString *)host{

}
- (void)packetCenter:(PacketCenter *)packetCenter didDisconnectWithError:(NSError *)err{

}

- (void)packetCenter:(PacketCenter *)packetCenter sendErrorPacket:(NSData *)packet{

}
- (void)packetCenter:(PacketCenter *)packetCenter didReceivedData:(NSData *)data{
    [self paserReceiveData:data];
}

#pragma mark get
- (PacketCenter *)centerPacket{
    if (!_centerPacket) {
        _centerPacket = [[PacketCenter alloc] init];
        _centerPacket.delegate = self;
    }
    return _centerPacket;
}
@end
